<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="栏目标题" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入栏目标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['textRead:textRead:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['textRead:textRead:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['textRead:textRead:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['textRead:textRead:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center"/>
      <el-table-column label="ID" align="center" width="80" prop="id"/>
      <el-table-column label="栏目标题" align="center" prop="name" :show-overflow-tooltip="true" width="200"/>
      <el-table-column label="内容预览" align="center" prop="content" width="400">
        <template slot-scope="scope">
          <div class="content-cell">{{ formatContent(scope.row.content) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="封面图片" align="center" prop="coverPath" width="100">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.coverPath" :src="scope.row.coverPath" :width="50" :height="50"/>
          <span v-else>-</span>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['textRead:textRead:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['textRead:textRead:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改栏目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="栏目标题" prop="name">
          <el-input v-model="form.name" placeholder="请输入栏目标题"/>
        </el-form-item>
        <el-form-item label="栏目内容" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="封面图片" prop="coverPath">
          <el-upload
            ref="upload"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :auto-upload="false"
            :on-remove="handleRemove"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleHttpRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传封面图片，大小不小于1MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArticle, getArticle, delArticle, addArticle, updateArticle, uploadFile, uploadContentImage } from "@/api/intergrity-recommend";
import ImageUpload from "@/components/ImageUpload";
import Editor from "@/components/Editor";
import imageCompression from "browser-image-compression";

export default {
  name: "TextRead",
  dicts: [],
  components: {
    ImageUpload,
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 栏目表格数据
      articleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null
      },
      // 表单参数
      form: {},
      // 封面文件列表
      fileList: [],
      // 待上传的封面文件
      uploadFile: null,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "栏目标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "栏目内容不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询栏目列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams
      };

      listArticle(params).then(response => {
        this.articleList = response.data.list || response.data || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
  },

  // 取消按钮
  cancel() {
    this.open = false;
    this.reset();
  },

  // 表单重置
  reset() {
      this.form = {
        id: null,
        name: null,
        content: null,
        coverPath: null
      };
      this.fileList = [];
      this.uploadFile = null;
    this.resetForm("form");
  },

  /** 搜索按钮操作 */
  handleQuery() {
    this.queryParams.pageNum = 1;
    this.getList();
  },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

  // 多选框选中数据
  handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

  /** 新增按钮操作 */
  handleAdd() {
    this.$router.push({
      path: '/intergrity-recommend/form/index',
      query: {
        operationType: 'add'
      }
    });
  },

    /** 修改按钮操作 */
  handleUpdate(row) {
    const id = row.id || this.ids[0];
    this.$router.push({
      path: '/intergrity-recommend/form/index',
      query: {
        operationType: 'edit',
        id: id
      }
    });
  },

  /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 检查文件大小
          if (this.uploadFile && this.uploadFile instanceof File) {
            const isLt1M = this.uploadFile.size / 1024 / 1024 < 1;
            if (isLt1M) {
              this.$modal.msgError("封面图片大小不能小于1MB!");
              return;
            }
          }

          // 判断是新增还是修改
          if (this.form.id != null) {
            // 修改：先上传图片，再保存文章
            if (this.uploadFile && this.uploadFile instanceof File) {
              try {
                console.log('修改模式：处理封面上传');
                const response = await this.uploadFileToServer(this.uploadFile);
                if (response && response.code === 200) {
                  this.form.coverPath = response.url;
                  this.saveArticle();
                }
              } catch (error) {
                console.error('封面上传失败:', error);
                if (error.message === '封面图片大小不能小于1MB!') {
                  // 提醒已经在beforeUpload中显示过了，这里不再重复显示
                } else {
                  this.$modal.msgError("封面上传失败: " + error.message);
                }
              }
            } else {
              this.saveArticle();
            }
          } else {
            // 新增：先保存文章获取ID，再上传图片
            try {
              console.log('新增模式：先保存文章获取ID');
              const articleResponse = await this.saveArticleForAdd();
              if (articleResponse && articleResponse.code === 200) {
                const articleId = articleResponse.data || articleResponse.id;
                console.log('获取到文章ID:', articleId);

                // 更新表单ID
                this.form.id = articleId;

                // 如果有封面图片需要上传
                if (this.uploadFile && this.uploadFile instanceof File) {
                  try {
                    console.log('新增模式：上传封面图片');
                    const response = await this.uploadFileToServer(this.uploadFile);
                    if (response && response.code === 200) {
                      this.form.coverPath = response.url;
                      // 更新文章封面路径
                      await this.updateArticleCover(articleId, response.url);
                    }
                  } catch (error) {
                    console.error('封面上传失败:', error);
                    this.$modal.msgError("封面上传失败: " + error.message);
                  }
                }

                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            } catch (error) {
              console.error('保存文章失败:', error);
              this.$modal.msgError("保存文章失败: " + error.message);
            }
          }
        }
      });
    },

    // 保存文章
    saveArticle() {
      if (this.form.id != null) {
        updateArticle(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addArticle(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },

    // 新增时保存文章并返回响应
    async saveArticleForAdd() {
      return await addArticle(this.form);
    },

    // 更新文章封面路径
    async updateArticleCover(articleId, coverPath) {
      const updateData = {
        id: articleId,
        coverPath: coverPath
      };
      return await updateArticle(updateData);
    },

    /** 删除按钮操作 */
  handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除栏目编号为"' + ids + '"的数据项？').then(function () {
        return delArticle(ids);
    }).then(() => {
      this.getList();
      this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

  /** 导出按钮操作 */
  handleExport() {
      this.download('textRead/textRead/export', {
      ...this.queryParams
      }, `textRead_${new Date().getTime()}.xlsx`)
    },

    // 封面上传请求处理
    handleHttpRequest(options) {
      console.log('封面上传请求处理:', options);
      this.uploadFileToServer(options.file);
    },

    // 文件上传前处理
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt1M = file.size / 1024 / 1024 < 1; // 检查是否小于1MB

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }

      if (isLt1M) {
        this.$message.error('封面图片大小不能小于1MB!');
        return false;
      }

      this.uploadFile = file;
      return false; // 阻止自动上传
    },

    // 文件变化处理
    handleFileChange(file, fileList) {
      console.log('封面文件变化处理:', file, fileList);
      if (fileList.length > 0) {
        const selectedFile = fileList[0].raw;
        // 检查文件大小是否小于1MB
        const isLt1M = selectedFile.size / 1024 / 1024 < 1;
        if (isLt1M) {
          this.$message.error('封面图片大小不能小于1MB!');
          // 清空文件列表，阻止文件被选中
          this.fileList = [];
          this.uploadFile = null;
          // 清空上传组件的文件列表
          if (this.$refs.upload) {
            this.$refs.upload.clearFiles();
          }
          return;
        }

        this.uploadFile = selectedFile;
        this.fileList = [fileList[fileList.length - 1]]; // 只保留最后一个文件
        console.log('更新 uploadFile:', this.uploadFile);
      } else {
        this.uploadFile = null;
        this.fileList = [];
        console.log('清空 uploadFile');
      }
    },

    // 文件移除处理
    handleRemove() {
      console.log('封面文件移除处理');
      this.uploadFile = null;
      this.form.coverPath = null;
      this.fileList = [];
      console.log('清空 uploadFile 和 coverPath');
    },

    // 修改后的上传方法
    async uploadFileToServer(file) {
      try {
        // 检查是否为虚拟File对象（带有url属性的OSS图片）
        if (file.url) {
          // 对于OSS图片，直接使用URL
          this.form.coverPath = file.url;
          this.$message.success('封面图片设置成功');
          return { code: 200, url: file.url };
        } else {
          // 压缩图片
          console.log('提交前压缩封面图片');
          const compressedFile = await this.compressImage(file, false); // 不检查最小大小限制

          const formData = new FormData();
          formData.append('file', compressedFile);

          console.log('调用封面上传API，ID:', this.form.id || 0);
          const response = await uploadFile(this.form.id || 0, formData);

          console.log('封面上传响应:', response);
          if (response.code === 200) {
            this.form.coverPath = response.url;
            this.$message.success('封面图片上传成功');
            return response;
          } else {
            throw new Error(response.msg || '上传失败');
          }
        }
      } catch (error) {
        console.error('上传失败:', error);
        // 如果是封面大小错误，避免重复显示提醒
        if (error.message === '封面图片大小不能小于1MB!') {
          // 提醒已经在beforeUpload中显示过了，这里不再重复显示
        } else {
          this.$message.error('封面图片上传失败: ' + error.message);
        }
        throw error;
      }
    },

    // 图片压缩方法
    async compressImage(file, checkMinSize = true) {
      const minSizeBytes = 1024 * 1024; // 1MB 下限
      const maxSizeBytes = 5 * 1024 * 1024; // 5MB 上限
      const skipCompressSizeBytes = 3 * 1024 * 1024; // 3MB

      // 检查文件是否小于最小大小（仅当checkMinSize为true时检查）
      if (checkMinSize && file.size < minSizeBytes) {
        throw new Error('封面图片大小不能小于1MB!');
      }

      // 如果文件小于 3MB，直接跳过压缩
      if (file.size < skipCompressSizeBytes) {
        console.log(`文件大小为 ${file.size} bytes，小于 3MB，跳过压缩`);
        return file;
      }

      // 所有图片都使用 Canvas 进行精确压缩，确保不会低于下限
      return await this.canvasCompress(file, minSizeBytes, maxSizeBytes);
    },

    // Canvas 进行精确压缩
    async canvasCompress(file, minSizeBytes, maxSizeBytes) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();

        img.onload = async () => {
          // 初始宽高
          let width = img.width;
          let height = img.height;

          // 计算缩放比例
          const ratio = width / height;

          // 如果图片很大，先进行初步缩放
          if (width > 2048 || height > 2048) {
            if (width > height) {
              width = 2048;
              height = 2048 / ratio;
            } else {
              height = 2048;
              width = 2048 * ratio;
            }
          }

          // 设置 canvas 尺寸
          canvas.width = width;
          canvas.height = height;

          // 绘制图片到 canvas
          ctx.drawImage(img, 0, 0, width, height);

          // 二分法查找合适的质量参数
          let quality = 1;
          let minQuality = 0.1;
          let maxQuality = 2;
          let attempts = 0;
          const maxAttempts = 10;

          let compressedBlob;

          while (attempts < maxAttempts) {
            attempts++;

            // 导出为 Blob
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', quality);
            });

            console.log(`第 ${attempts} 次压缩尝试，质量: ${quality}, 大小: ${compressedBlob.size} bytes`);

            // 检查大小是否符合要求
            if (compressedBlob.size >= minSizeBytes && compressedBlob.size <= maxSizeBytes) {
              console.log('压缩成功，大小符合要求');
              break;
            }

            // 调整质量参数
            if (compressedBlob.size > maxSizeBytes) {
              // 太大了，降低质量
              maxQuality = quality;
              quality = (minQuality + quality) / 2;
            } else {
              // 太小了，提高质量
              minQuality = quality;
              quality = (quality + maxQuality) / 2;
            }

            // 如果质量调整过小，可能无法达到最小大小要求
            if (quality < 0.01) {
              console.warn('质量参数过低，无法达到最小大小要求');
              break;
            }
          }

          // 如果最终结果还是太小，使用最小质量重新压缩
          if (compressedBlob.size < minSizeBytes) {
            console.warn(`压缩后文件过小 (${compressedBlob.size} bytes)，使用最小质量重新压缩`);
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', 0.95);
            });
          }

          // 转换为 File 对象
          const compressedFile = new File([compressedBlob], file.name, {
            type: 'image/jpeg',
            lastModified: Date.now()
          });

          console.log(`最终压缩结果: ${compressedFile.size} bytes`);
          resolve(compressedFile);
        };

        img.onerror = () => {
          reject(new Error('图片加载失败'));
        };

        // 读取文件
        const reader = new FileReader();
        reader.onload = e => {
          img.src = e.target.result;
        };
        reader.onerror = () => {
          reject(new Error('文件读取失败'));
        };
        reader.readAsDataURL(file);
      });
    },

    // 格式化内容显示
    formatContent(content) {
      if (!content) return '-';
      // 移除HTML标签
      const plainText = content.replace(/<[^>]*>/g, '');
      // 截取前100个字符
      return plainText.length > 100 ? plainText.substring(0, 100) + '...' : plainText;
    }
  }
};
</script>

<style scoped>
.content-cell {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
}
</style>
